# encoding:utf-8
from time import sleep
import requests
import logging
from utils.interface_encryption.AES_SecretKey import random_string, aes_encrypt
from utils.interface_encryption.RSA_SecretKey import encrypt_message
from utils.others_tool.other_tool import find_all_data
import hashlib
from config.global_variable import ENV_DICT, public_key_pem
from utils.others_tool.verification_code_recognition import verification_code

header = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.129 Safari/537.36'
}


class Authentication():
    '''
    接口鉴权：cooking,session,token,sign
    '''

    def __init__(self, username, password, url):
        self.username = username
        self.password = password
        self.url = url
        logging.captureWarnings(True)

    def auth_wutong(self):
        '''
        获取身份信息，创建一个session
        梧桐系统登录鉴权
        :return:
        '''
        # 登录地址
        loginURL = self.url + r'/account/public/page/login.html'
        s = requests.session()
        params = {"account_types": "DOCTOR STAFF", "login_types": "PHONE_PASSWORD PHONE", "app_name": "WUTONG",
                  "platform_source": "WUTONG", "target_page": ENV_DICT.get('target_page') }
        result = s.get(loginURL, params=params, headers=header).text
        token = find_all_data(result, LB='<input id="login-unq-token" type="hidden" value="', RB='">')[0]

        # 查询接口：通过手机号查询账户
        queryURL = self.url + r"/account/public/api/login_account/query"
        json = {"phone": self.username}
        result_1 = s.post(queryURL, json=json, headers=header).json()
        accountType = result_1["data"][0]["accountType"]

        # H5登录
        H5loginURL = self.url + r"/account/public/api/login_h5/login"
        json = {"accountType": accountType, "loginType": "PHONE_PASSWORD", "loginKey": self.password,
                "loginUnqToken": token, "platformSource": "WUTONG",
                "loginName": self.username}
        result_2 = s.post(H5loginURL, json=json, headers=header).json()
        loginTicket = result_2["data"]['loginTicket']
        targetPage = result_2["data"]['targetPage']

        # 获取登录COOKING
        getCookingURL = self.url + r"/account/api/login/success"
        params = {"target_page": targetPage, "login_ticket": loginTicket}
        result_3 = s.get(getCookingURL, params=params, headers=header).json()

        # 将获取的信息加入session中
        cooking_value = result_3["data"]["cookieValue"]
        cooking_name = result_3["data"]["cookieName"]
        header['Cookie'] = cooking_name + "=" + cooking_value
        s.headers.update(header)

        return s

    def auth_feigong(self):
        '''非公系统登录鉴权'''
        s = requests.session()
        loginURL = self.url + '/supda-auth/oauth/token'
        headers = {
            'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                           '(KHTML, like Gecko) Chrome/112.0.0.0 Safari/537.36'),
            'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
            'Origin': ENV_DICT.get('origin'),
        }
        body = {
            "tenantId": "",
            "username": self.username,
            "password": hashlib.md5(self.password.encode(encoding='UTF-8')).hexdigest(),
            "grant_type": "password",
            "scope": "all",
            "type": "account"
        }
        response = s.post(loginURL, data=body, headers=headers)
        result = response.json()
        Supda_Auth = result.get('access_token')
        if Supda_Auth:
            headers['Supda-Auth'] = f'bearer {Supda_Auth}'
        s.headers.update(headers)

        return s

    def auth_weight(self):
        '''减重系统登录鉴权'''
        s = requests.session()
        loginURL = self.url + '/rosefinch-auth/oauth/token'
        headers = {
            'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                           '(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'),
            'Authorization': 'Basic c2FiZXI6c2FiZXJfc2VjcmV0',
            'Origin': ENV_DICT.get('origin'),
        }
        body = {
            "tenantId": "",
            "username": self.username,
            "password": hashlib.md5(self.password.encode(encoding='UTF-8')).hexdigest(),
            "grant_type": "password",
            "scope": "all",
            "type": "account"
        }
        response = s.post(loginURL, params=body, headers=headers)
        result = response.json()
        Rosefinch_auth = result.get('access_token')
        if Rosefinch_auth:
            headers['rosefinch-Auth'] = f'bearer {Rosefinch_auth}'
        s.headers.update(headers)

        return s


    def auth_Internet_hospital(self):
        '''
        互联网医院登录鉴权
        涉及ocr识别验证码
        RSA加密
        '''
        s = requests.session()

        username = self.username
        password = encrypt_message(public_key_pem, self.password)
        login_url = self.url + "/cms/auth/login"
        code_url = self.url + '/cms/auth/code'

        # 识别验证码的最大次数
        max_attempts = 10
        # 登录的最大次数
        max_retries = 3

        def get_captcha():
            # ocr识别数学运算验证码,识别准确率为40%，经实验，最多可在5次内识别成功
            attempt = 0
            result = "计算出错"
            uuid = ''
            while result == "计算出错" and attempt < max_attempts:
                attempt += 1
                print(f"OCR 识别尝试次数: {attempt}")
                response = s.get(code_url)
                data = response.json().get('data', {})
                uuid = data.get('uuid', '')
                base64_str = data.get('img', '')
                result = verification_code(base64_str)
            return result, uuid

        for retry in range(max_retries):
            if retry > 0:
                print(f"验证码错误，重试 {retry}/{max_retries}")
            code, uuid = get_captcha()
            json_data = {
                "code": code,
                "password": password,
                "smsCode": "1234",
                "username": username,
                "uuid": uuid
            }
            response_1 = s.post(login_url, json=json_data, headers=header)
            response_msg = response_1.json().get('msg', '')
            if response_msg == "成功":
                header['Authorization'] = response_1.json()['data']['token']
                s.headers.update(header)
                break
            elif response_msg == "验证码错误":
                print(f"验证码错误，重试 {retry + 1}/{max_retries}")
                sleep(1)
            else:
                print("发生未知错误，终止重试。")
                break
        return s

    def auth_TH(self):
        '''
        随访系统接口鉴权
        AES加密
        '''
        s = requests.session()

        login_url = self.url + '/nethos/platformApi/admin/login/sysUser'
        username = self.username
        key = random_string(16)
        password = aes_encrypt(self.password, key)
        random64 = random_string()
        json_data = {
            "captcha": '1234',
            "id": random64,
            "password": password,
            "type": 2,
            "username": username
        }
        headers = {
            'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
                           '(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36'),
            'Codekey': key
        }
        response = s.post(login_url,json=json_data, headers=headers)
        header['Authorization'] = response.json()['data']['authInfo']
        s.headers.update(header)

        return s





if __name__ == '__main__':
    s = Authentication("17600000001", "123456Aa", "https://test-weight-api.child-healthy.com").auth_TH()
    result = s.get('https://followup-test.child-healthy.cn/nethos/platformApi/admin/sysUser/detail/current').json()
    print(result)